/**
 * zmn员工模块-员工编辑
 * 文件命名格式：zmn.模块.表/功能.js
 * @author heguanghua
 * @since 2020/04/23 13:45
 */
layui.define(['form','zmnApp', 'zmnSelect', 'laydate'], function (exports) {
    let $ = layui.$;
    let form = layui.form;
    let layer = layui.layer;
    let laydate = layui.laydate;
    let zmnApp = layui.zmnApp;
    let zmnSelect = layui.zmnSelect;
    let mobile = json.staff.mobile; // 明文号码
    let pattern = /^1[0123456789]\d{9}$/;

    form.render(null, "zmn-form");

    if (json.staff.entryTime != null) {
        laydate.render({elem: "#entryTime", type: "date", value: new Date(json.staff.entryTime)});
    } else {
        laydate.render({elem: "#entryTime", type: "date"});
    }

    if (json.staff.becomeFormalTime != null) {
        laydate.render({elem: "#becomeFormalTime", type: "date", value: new Date(json.staff.becomeFormalTime)});
    } else {
        laydate.render({elem: "#becomeFormalTime", type: "date"});
    }

    if (json.staff.startWorkTime) {
        laydate.render({
            elem: "#workTime",
            type: "time",
            range: true,
            value: json.staff.startWorkTime + " - " + json.staff.stopWorkTime
        });
    } else {
        laydate.render({elem: "#workTime", type: "time", range: true, value: '08:00:00 - 22:00:00'});
    }

    // 部门下拉组件
    let deptTree = function (orgId) {
        if (orgId == null) {
            orgId = 0; // 后端Integer类型接收
        }
        zmnSelect.deleteXmSelect("deptId");
        var objMap = zmnSelect.select({
            'deptId': {
                isRadio: true, //单选标识：true-单选；false-多选
                selectedValues: [json.staff.deptId == null ? '' : json.staff.deptId], //已选中值（用于回显)
                tree: {
                    enable: true,
                    //是否展示三角图标
                    showFolderIcon: true,
                    //非严格模式
                    strict: false,
                },
                propMap: {  //选项参数映射配置
                    name: "deptName",   //显示值
                    value: "deptId"  //选中值
                },
                remote: { //远程获取下拉数据
                    enable: true, //开关：true-开启；false-关闭
                    url: '/common/dept/listDeptTree.action?orgId=' + orgId, //服务url
                },
            }
        });
        objMap['deptId'].update({
            filterable: false,
            autoRow: false,
            model: {label: {type: 'text'}},
            on: function (data) {
                if (data.isAdd) {
                    return data.change.slice(0, 1)
                }
            }
        })
    }

    // 组织架构
    zmnSelect.selectlOrganizes(
        {
            platSelectId: 'plat', //平台ID
            orgTwoSelectId: 'orgTwoId', //大区ID
            orgThrSelectId: 'orgId', //子公司ID
        },
        {
            platSelectId: {
                selectedValues: json.plat,
                events: {
                    changed: function (values) {
                        if(zmnUtil.isNotEmptyNull(values)){
                            deptTree(values);
                        }
                    }
                }
            },
            orgTwoSelectId: {
                selectedValues: json.orgTwoId,
                events: {
                      changed: function (values) {
                          if(zmnUtil.isNotEmptyNull(values)){
                              deptTree(values);
                          }
                      }
                }
            },
            orgThrSelectId: {
                isRadio: true,
                selectedValues: json.orgId,
                events: {
                    changed: function (values) {
                        if(zmnUtil.isNotEmptyNull(values)){
                            deptTree(values);
                        }
                    }
                }
            }
        }
    );

        //${obj.staffId != null && obj.type != 3 && obj.type != 6 && obj.type != 8}
    if(json.staff.staffId != null && json.staff.type != 3 && json.staff.type != 6 && json.staff.type != 8){

            xmSelect.get('#plat', true).update({disabled: true});
            xmSelect.get('#orgTwoId', true).update({disabled: true});
            xmSelect.get('#orgId', true).update({disabled: true});
    }


    // 加载部门组件 回显部门数据
    if (appUtil.notNull(json.orgId)) {
        deptTree(json.orgId);
    } else if (appUtil.notNull(json.orgTwoId)) {
        deptTree(json.orgTwoId);
    } else {
        deptTree(json.plat);
    }

    // 省市下拉组件
    zmnSelect.selectlAreas({
        provinceSelectId: 'workPlaceProvince',
        citySelectId: 'workPlaceCity',
    }, {
        provinceSelectId: {
            selectedValues: json.staff.workPlaceProvince == null ? null : json.staff.workPlaceProvince,
        },
        citySelectId: {
            isRadio: true,
            selectedValues: json.staff.workPlaceCity == null ? null : json.staff.workPlaceCity,
        },
    });

    zmnSelect.searchStaff('leaderId', {
        searchedValue: json.staff.leaderName,
        selectedValues: json.staff.leaderId,
        isRadio: true,
        remote: {
            limitPermit: false,
            events: {
                extendParams: function () {
                    return {
                        status: null,
                    }
                }
            }
        },
        events: {
            changed: function (values) {
            }
        }
    });

    // 自定义验证规则
    form.verify({
        isMobile: function (value) {
            if (appUtil.notNull(value)) {
                if (appUtil.isNull(json.staff.staffId) || (appUtil.notNull(json.staff.staffId) && json.hasMobileAuth)) {
                    if (!pattern.test(value)) {
                        return "请输入正确手机号!";
                    }
                }
            }
        },
        exportLimit: function (value) {
            if (zmnUtil.isEmptyNull(value)) {
                return;
            }
            if (!zmnUtil.isNumber(value, false)) {
                return "请填写整数";
            }
        },
    });

    // 提交
    form.on('submit(zmn-form-submit)', function (obj) {
        let data = obj.field;

        const workTime = data.workTime.split(' - ')
        data.startWorkTime = workTime[0]
        data.stopWorkTime = workTime[1]

        if (data.postId) {
            debugger
            const role = json.roles.filter(item => item.roleId === parseInt(data.postId))[0];
            data.post = role.roleName;
        }

        if (data.deptId == null || data.deptId == "") {
            layer.msg("所属部门不能为空", {"icon": 2});
            return false;
        }
        if (data.workPlaceProvince == null || data.workPlaceProvince == "" || data.workPlaceCity == null || data.workPlaceCity == "") {
            layer.msg("工作地点不能为空", {"icon": 2});
            return false;
        }
        if (data.mobile.indexOf("*") != -1) {
            // 使用明文号码
            data.mobile = mobile;
        }
        if (!pattern.test(data.mobile)) {
            layer.msg("请输入正确手机号!", {"icon": 2});
            return false;
        }
        if (data.leaderId == null || data.leaderId == "") {
            layer.msg("直线经理不能为空", {"icon": 2});
            return false;
        }
        let url = zmnApp.SYS_BASE_URL + "/staff/modify/addEdit.action";
        let jumpStop = false;
        $.ajax({
            async: false,
            type: "POST", url: url,
            contentType: "application/json", dataType: "json", data: JSON.stringify(data),
            success: function (json) {
                let message = json.status == zmnStatus.SUCCESS ? "操作成功！" : json.message;
                layer.msg(message);
                if (json.status == zmnStatus.SUCCESS && !zmnUtil.isNotZeroInteger(data.staffId)) {
                    zmnPage.direct("/staff/detail.action?staffId=" + json.data, 0);
                } else if (json.status == zmnStatus.FAIL) {
                    jumpStop = true;
                }
                return;
            },
            error: function (XMLHttpRequest, tstaffStatus, errorThrown) {
            }
        })
        if (jumpStop || data.staffId * 1 > 0) {
            return false;
        }
    });

    // 取消
    $(document).on('click', '#cancel', function () {
        parent.layui.admin.events.closeThisTabs();
    });

    // 禁用
    if (json.staff.staffId != null && json.staff.type != 3 && json.staff.type != 6 && json.staff.type != 8) {
        $("#realName").attr("disabled", true);
        $("#realName").addClass("layui-disabled");
        $("#pinyinName").attr("disabled", true);
        $("#pinyinName").addClass("layui-disabled");
        $("#mobile").attr("disabled", true);
        $("#mobile").addClass("layui-disabled");
        $("#mail").attr("disabled", true);
        $("#mail").addClass("layui-disabled");
        $("#post").attr("disabled", true);
        $("#post").addClass("layui-disabled");
        $("#entryTime").attr("disabled", true);
        $("#entryTime").addClass("layui-disabled");
        $("#becomeFormalTime").attr("disabled", true);
        $("#becomeFormalTime").addClass("layui-disabled");

        $("#deptId").attr("style", "pointer-events: none;"); // 禁用
        $("#workPlaceProvince").attr("style", "pointer-events: none;"); // 禁用
        $("#workPlaceCity").attr("style", "pointer-events: none;"); // 禁用

        // 禁用工作时间
        $("#workTime").attr("disabled", true);
        $("#workTime").addClass("layui-disabled");

        // 禁用直线经理
        zmnSelect.getXmSelect("leaderId").update({disabled: true});
    }

    //对外暴露的接口
    exports('staff_detail', {});
});
